from urllib.request import Request

from flask import Blueprint,render_template, jsonify, redirect, url_for, session
from exts import mail,db
from flask_mail import Message
from flask import request
import string
import random
from models import EmailCaptchaModel,UserModel
from .forms import RegisterForm, LoginForm
from werkzeug.security import generate_password_hash,check_password_hash
bp = Blueprint('auth', __name__, url_prefix='/auth')


def tom_hash(password_open):
    return generate_password_hash(password_open, method='pbkdf2:sha256')


@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                print("邮箱在数据库中不存在！")
                return redirect(url_for('auth.login'))
            if check_password_hash(user.password, password):
                #cookie
                #cookie 中不适合存储太多的数据，只适合存储少量的数据
                #cookie 一般用来存放登录授权的东西
                #flaks 中的session，是经过加密后存储在cookie中的
                session['user_id'] = user.id
                return redirect('/')
            else:
                print("密码错误！")
                return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for('auth.login'))#再次发送请求页面




#GET 从服务器上获取数据
#POST 将客户端的数据提交给服务器
@bp.route('/register',methods=['GET','POST'])
def register():
    if request.method == "GET":
        return render_template("register.html")
    else:
        # 验证用户提交的邮箱和验证码是否对应且正确
        # 表单创建:flask-wtf (wtforms)
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            user = UserModel(email=email,username=username,password=tom_hash(password))
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('auth.login'))
        else:
            print(form.errors)
            return redirect(url_for('auth.register'))


@bp.route('/logout')
def logout():
    #先将cookie delete
    session.clear()
    return redirect("/")




#如果没有指定methods参数，那么默认就是GET请求
@bp.route('/captcha/email')
def get_email_captcha():
    # /captcha/email?email=2177696531@qq.com
    email = request.args.get('email')
    #数字，字母，符号组合
    source = string.digits * 4
    captcha = random.sample(source,4)
    captcha = ''.join(captcha)
    # print(source, type(source))
    # print(captcha,type(captcha))
    message = Message(subject='Registration Verification Code', recipients=[email], body=f'Your registration verification code is:\n {captcha}\t, don\'t share it with anyone else.' )
    mail.send(message)
    # memcached / redis(stronger)
    # 用数据库去存储（比较慢，但是对我们小网站时ok的）
    email_captcha = EmailCaptchaModel(email=email, captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    # RESTFUL API
    # {code:200/ 400 /500, message: "", data:{}}
    return jsonify({"code": 200, "message":"", "data":None})


@bp.route('/mail/test')
def mail_test():
    message = Message(subject='test mail', recipients=['10225101490@stu.ecnu.edu.cn','2177686531@qq.com'],body=' ')
    mail.send(message)
    return "Mail Sending successfully!"